package com.ssy.lingxi.system.service.impl;

import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.constant.CountryCodeEnum;
import com.ssy.lingxi.member.merchant.api.feign.paas.CountryCodeControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.paas.CountryCodeUpdateInsertVO;
import com.ssy.lingxi.platform.manage.api.feign.paas.CountryAreaPAASControllerFeign;
import com.ssy.lingxi.platform.manage.api.model.dto.countryarea.CountryAreaPAASDTO;
import com.ssy.lingxi.system.dao.CountryAreaRepository;
import com.ssy.lingxi.system.dao.CurrencyRepository;
import com.ssy.lingxi.system.dao.LanguageRepository;
import com.ssy.lingxi.system.dao.SiteRepository;
import com.ssy.lingxi.system.dto.request.*;
import com.ssy.lingxi.system.dto.response.CountryAreaListResponse;
import com.ssy.lingxi.system.dto.response.MiddlegroundUserLoginResponse;
import com.ssy.lingxi.system.entity.CountryArea;
import com.ssy.lingxi.system.entity.Currency;
import com.ssy.lingxi.system.entity.Language;
import com.ssy.lingxi.system.entity.Site;
import com.ssy.lingxi.system.service.CountryAreaService;
import com.ssy.lingxi.system.utils.UserDetailsUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

@Service
public class CountryAreaServiceImpl implements CountryAreaService {

    @Autowired
    CountryAreaRepository countryAreaRepository;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    CurrencyRepository currencyRepository;
    @Autowired
    LanguageRepository languageRepository;
    @Autowired
    UserDetailsUtil userDetailsUtil;
    @Resource
    CountryAreaPAASControllerFeign countryAreaControllerFeign;
    @Resource
    CountryCodeControllerFeign countryCodeControllerFeign;

    @Resource
    SiteRepository siteRepository;
    /**
     * 查询国家地区列表数据
     * @param request 接口参数
     */
    @Override
    public Wrapper<PageData<CountryAreaListResponse>> countryAreaList(CountryAreaListRequest request) {
        StringBuilder sbList=new StringBuilder();
        StringBuilder sbCount=new StringBuilder();
        StringBuilder sbCondition=new StringBuilder();
        sbList.append("SELECT ca.ID,ca.code,ca.name as name,ca.name_en nameEn,ca.tel_code as telCode, ca.tel_number as telNumber,ca.state,C.name_en as currencyNameEn,c.name as currencyName,l.name as languageName,ca.img_url as imgUrl FROM cf_country_area ca LEFT JOIN cf_currency C ON ca.currency_id = C.ID LEFT JOIN cf_language l ON ca.language_id = l.ID");
        sbCount.append("SELECT count(ca.id) FROM cf_country_area ca LEFT JOIN cf_currency C ON ca.currency_id = C.ID LEFT JOIN cf_language l ON ca.language_id = l.id");
        sbCondition.append(" where 1=1 ");
        if(null!=request &&null!=request.getCode() &&!request.getCode().isEmpty()){
            sbCondition.append(" AND  ca.code = '");
            sbCondition.append(request.getCode());
            sbCondition.append("' ");
        }
        if(null!=request &&null!=request.getName() &&!request.getName().isEmpty()){
            sbCondition.append(" AND  ca.name like  '%");
            sbCondition.append(request.getName());
            sbCondition.append("%'");
        }
        if(null!=request &&null!=request.getNameEn() &&!request.getNameEn().isEmpty()){
            sbCondition.append(" AND  ca.name_en like  '%");
            sbCondition.append(request.getNameEn());
            sbCondition.append("%'");
        }
        sbList.append(sbCondition.toString());
        sbCount.append(sbCondition.toString());
        sbList.append(" limit ");
        sbList.append(request.getPageSize());
        sbList.append(" OFFSET ");
        sbList.append(request.getCurrent());
        Long count = jdbcTemplate.queryForObject(sbCount.toString(), Long.class);
        List<CountryAreaListResponse> countryAreaListResponse = jdbcTemplate.query(sbList.toString(),  new BeanPropertyRowMapper(CountryAreaListResponse.class));
        return Wrapper.success(new PageData<>(count,countryAreaListResponse));
    }

    /**
     * 新加国家设置
     *
     * @param request 接口参数
     */
    @Transactional
    @Override
    public Wrapper countryAreaAdd(HttpServletRequest httpServletRequest,CountryAreaAddRequest request) {
        MiddlegroundUserLoginResponse loginUserDetails = userDetailsUtil.getLoginUserDetails(httpServletRequest);

        CountryCodeEnum codeEnum = CountryCodeEnum.findByCode(request.getTelCode());
        if(codeEnum == null) {
            return Wrapper.fail("电话号码不正确，例如：中国的号码是 +86");
        }

        if(!codeEnum.getCn().equals(request.getName())) {
            return Wrapper.fail("国家名字与电话号码不匹配," + request.getTelCode() + "是" + codeEnum.getCn() + "的电话号码");
        }

        if(!codeEnum.getEn().toLowerCase().equals(request.getNameEn().toLowerCase())) {
            return Wrapper.fail("国家英文名字不正确, " + codeEnum.getCn() + "的英文名称是" + codeEnum.getEn());
        }

        List<CountryArea> areaList = countryAreaRepository.findAll();
        if(areaList.stream().anyMatch(area -> area.getNameEn().equals(request.getNameEn()))) {
            return Wrapper.fail("国家英文名字已存在,请修改后重新提交");
        }

        if(areaList.stream().anyMatch(area -> area.getName().equals(request.getName()))) {
            return Wrapper.fail("国家名字已存在,请修改后重新提交");
        }

        if(areaList.stream().anyMatch(area -> area.getCode().equals(request.getCode()))) {
            return Wrapper.fail("国家地区代码已存在,请修改后重新提交");
        }

        //会员服务
        CountryCodeUpdateInsertVO updateInsertVO = new CountryCodeUpdateInsertVO();
        updateInsertVO.setCode(request.getTelCode());
        updateInsertVO.setPhoneLength(request.getTelNumber());
        Wrapper<Void> result = countryCodeControllerFeign.updateOrInsertCountryCode(updateInsertVO);
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(result.getCode(), result.getMessage());
        }

        CountryArea countryArea=new CountryArea();
        BeanUtils.copyProperties(request,countryArea);
        countryArea.setCreateTime(System.currentTimeMillis());
        countryArea.setCreateRoleId(loginUserDetails.getId());
        countryArea.setLanguageId(request.getLanguageId());
        countryArea.setCurrencyId(request.getCurrencyId());
        countryArea.setImgUrl(request.getImgUrl());
        countryAreaRepository.save(countryArea);

        //平台后台
        CountryAreaPAASDTO synCountryAreaRequest = new CountryAreaPAASDTO();
        BeanUtils.copyProperties(countryArea, synCountryAreaRequest);
        return countryAreaControllerFeign.add(synCountryAreaRequest);
    }

    /**
     * 批量删除国家
     *
     * @param request
     * @author wrc
     * @date 2020/6/2
     */
    @Transactional
    @Override
    public Wrapper countryAreaDelete(CountryAreaDeleteRequest request) {
        List<CountryArea> allById = countryAreaRepository.findAllById(request.getIds());
        for (CountryArea countryArea:allById ) {
            if(EnableDisableStatus.DISABLE.getCode().equals(countryArea.getState())){
                return Wrapper.fail("国家使用状态中无法删除");
            }
        }

        //会员服务
        for (CountryArea countryArea : allById) {
            CountryCodeUpdateInsertVO upsertVO = new CountryCodeUpdateInsertVO();
            upsertVO.setCode(countryArea.getTelCode());
            upsertVO.setPhoneLength(0);
            Wrapper<Void> result = countryCodeControllerFeign.deleteCountryCode(upsertVO);
            if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
                return Wrapper.fail(result.getCode(), result.getMessage());
            }
        }

        //平台后台
        CountryAreaPAASDTO synCountryAreaRequest = new CountryAreaPAASDTO();
        synCountryAreaRequest.setIds(request.getIds());
        Wrapper<?> wrapper = countryAreaControllerFeign.delete(synCountryAreaRequest);
        if(wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(wrapper.getCode(), wrapper.getMessage());
        }

        countryAreaRepository.deleteCountryAreaByIdIn(request.getIds());

        return Wrapper.success();
    }

    /**
     * 修改国家信息
     *
     * @param request
     * @author wrc
     * @date 2020/6/2
     */
    @Transactional
    @Override
    public Wrapper countryAreaUpdate(CountryAreaUpdateRequest request) {
        CountryCodeEnum codeEnum = CountryCodeEnum.findByCode(request.getTelCode());
        if(codeEnum == null) {
            return Wrapper.fail("电话号码不正确，例如：中国的号码是 +86");
        }

        if(!codeEnum.getCn().equals(request.getName())) {
            return Wrapper.fail("国家名字与电话号码不匹配," + request.getTelCode() + "是" + codeEnum.getCn() + "的电话号码");
        }

        if(!codeEnum.getEn().toLowerCase().equals(request.getNameEn().toLowerCase())) {
            return Wrapper.fail("国家英文名字不正确, " + codeEnum.getCn() + "的英文名称是" + codeEnum.getEn());
        }

        Optional<CountryArea> byId = countryAreaRepository.findById(request.getId());
        if(!byId.isPresent()){
            return Wrapper.fail("国家信息不存在请检查参数");
        }
        if(byId.get().getState().equals(EnableDisableStatus.ENABLE.getCode())){
            return Wrapper.fail("国家状态启用中无法修改");
        }

        //会员服务
        CountryCodeUpdateInsertVO updateInsertVO = new CountryCodeUpdateInsertVO();
        updateInsertVO.setCode(request.getTelCode());
        updateInsertVO.setPhoneLength(request.getTelNumber());
        Wrapper<Void> result = countryCodeControllerFeign.updateOrInsertCountryCode(updateInsertVO);
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(result.getCode(), result.getMessage());
        }

        CountryArea countryArea=new CountryArea();
        BeanUtils.copyProperties(request,countryArea);
        countryArea.setUpdateTime(System.currentTimeMillis());
        countryArea.setImgUrl(request.getImgUrl());
        countryAreaRepository.save(countryArea);

        CountryAreaPAASDTO synCountryAreaRequest = new CountryAreaPAASDTO();
        BeanUtils.copyProperties(countryArea, synCountryAreaRequest);
        return countryAreaControllerFeign.update(synCountryAreaRequest);
    }

    /**
     * 查国家详情
     * @param request
     * @author wrc
     * @date 2020/6/2
     */
    @Override
    public Wrapper<CountryAreaListResponse> countryAreaDetails(CountryAreaDetailsRequest request) {
        CountryAreaListResponse countryAreaListResponse=new CountryAreaListResponse();
        Optional<CountryArea> byId = countryAreaRepository.findById(request.getId());
        if(!byId.isPresent()){
            return Wrapper.fail(ResponseCode.DATA_VALID_FAIL,"国家信息不存在");
        }
        CountryArea countryArea = byId.get();
        BeanUtils.copyProperties(countryArea,countryAreaListResponse);
        if(null!=countryArea.getCurrencyId()){
            //查询语言名字
            Optional<Currency> currency = currencyRepository.findById(countryArea.getCurrencyId());
            countryAreaListResponse.setCurrencyName(!currency.isPresent()?"":currency.get().getName());
            countryAreaListResponse.setCurrencyNameEn(!currency.isPresent()?"":currency.get().getNameEn());
            countryAreaListResponse.setCurrencyId(!currency.isPresent()?0L:currency.get().getId());
        }
        if(null!=countryArea.getLanguageId()){
            //和币制名字
            Optional<Language> language = languageRepository.findById(countryArea.getLanguageId());
            countryAreaListResponse.setLanguageName(!language.isPresent()?"":language.get().getName());
            countryAreaListResponse.setLanguageId(!language.isPresent()?0L:language.get().getId());
        }
        return Wrapper.success(countryAreaListResponse);
    }

    /**
     * 查询所有国家信息
     *
     * @author wrc
     * @date 2020/6/3
     */
    @Override
    public Wrapper<List<CountryArea>> countryAreaAll() {
        List<CountryArea> countryAreas = countryAreaRepository.queryByStateEquals(CommonConstant.State.STATE_START);
        return Wrapper.success(countryAreas);
    }

    /**
     * 停用国家配置
     *
     * @param request
     * @author wrc
     * @date 2020/6/3
     */
    @Override
    public Wrapper countryAreaStop(CountryAreaStopRequest request) {
        CountryArea countryArea = countryAreaRepository.findById(request.getId()).orElse(null);
        if(countryArea == null){
            return Wrapper.fail("国家信息不存在请检查参数");
        }
        if(CommonConstant.State.STATE_STOP.equals(request.getState())){
            List<Site> site = siteRepository.queryByCountryIdEquals(request.getId());
            if(null!=site&&site.size()>0){
                return Wrapper.fail("国家信息与站点存在关联不能停用");
            }
        }

        //会员服务
        CountryCodeUpdateInsertVO updateInsertVO = new CountryCodeUpdateInsertVO();
        updateInsertVO.setCode(countryArea.getTelCode());
        updateInsertVO.setPhoneLength(countryArea.getTelNumber());
        Wrapper<Void> result = CommonConstant.State.STATE_STOP.equals(request.getState()) ? countryCodeControllerFeign.deleteCountryCode(updateInsertVO) : countryCodeControllerFeign.updateOrInsertCountryCode(updateInsertVO);
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(result.getCode(), result.getMessage());
        }

        countryArea.setUpdateTime(System.currentTimeMillis());
        countryArea.setState(request.getState());
        countryAreaRepository.save(countryArea);

        //平台后台
        CountryAreaPAASDTO synCountryAreaRequest = new CountryAreaPAASDTO();
        BeanUtils.copyProperties(countryArea, synCountryAreaRequest);
        return countryAreaControllerFeign.enable(synCountryAreaRequest);
    }


}
